const Router = require('@koa/router');
const mongoose = require('mongoose');
const { getBody } = require('../utils/getBody')
const PersonalDetail = mongoose.model('PersonalDetail')

const router = new Router({
    prefix: '/personaldetail',
})

//personaldetail/add
router.post('/add', async (ctx) => {
    const {
        account,
        realName,
        sex,
        birthday,
        phoneNumber,
        home,
        marriage
    } = getBody(ctx)
    const personalDetail = new PersonalDetail({
        account,
        realName,
        sex,
        birthday,
        phoneNumber,
        home,
        marriage
    });
    console.log('account', account);
    //如果已经存在account了,不允许再添加
    const one = await PersonalDetail.findOne({
        account,
    }).exec()
    if (one) {
        //更改
        one.account = account
        one.realName = realName
        one.sex = sex
        one.birthday = birthday
        one.phoneNumber = phoneNumber
        one.home = home
        one.marriage = marriage
        const res = await one.save()
        ctx.body = {
            code: 200,
            data: res,
            msg: '更新成功'
        }
    } else {
        const res = await personalDetail.save()
        ctx.body = {
            data: res,
            code: 200,
            msg: '添加个人信息成功'
        }
    }
})

//personaldetail/search
router.post('/search', async (ctx) => {
    const {
        account,  //对应auth表的_id 
    } = getBody(ctx)
    console.log('打印account', account);
    const one = await PersonalDetail.findOne({
        account: account,
    }).exec()
    if (one) {
        ctx.body = {
            msg: '已获取当前用户',
            data: one,
            code: 200
        }
        return
    } else {
        ctx.body = {
            msg: '无法获取当前用户',
            code: 0
        }
    }

})
router.get('/list', async (ctx) => {
    let {
        page = 1,
        size = 5,
        keyword = ""
    } = ctx.query
    page = Number(page)
    size = Number(size)
    let reg = new RegExp(keyword, "gim")
    const list = await PersonalDetail
        .find({ "realName": { $regex: reg } }) //员工姓名模糊搜索
        .sort({ _id: -1 }) //-1倒序
        .skip((page - 1) * size)
        .limit(size).exec()
    const total = await PersonalDetail.countDocuments().exec()
    ctx.body = {
        msg: '获取员工列表成功',
        data: {
            list,
            page,
            size,
            total
        },
        code: 200
    }
})
/**删除 */
router.delete('/:id', async (ctx) => {
    const {
        id
    } = ctx.params
    const res = await PersonalDetail.deleteOne({
        _id: id
    })
    ctx.body = {
        code: 200,
        msg: '删除成功',
        data: res
    }
})
module.exports = router